/**
 * 全局异常处理
 */
const {HttpException} = require('../core/http-exception');

const catchError = async (ctx, next) => {
    try {
        await next()
    } catch (error) {
        const isHttpException = error instanceof HttpException
        const isDev = global.config.environment === 'dev'
        if (isDev && !isHttpException) {
            throw error
        }
        // 错误类型是httpException 一个已知错误
        if (error instanceof HttpException) {
            ctx.body = {
                msg: error.msg,// msg
                error_code: error.errorCode, // errorCode
                request: `${ctx.method}${ctx.path}`// http code
            }
            ctx.status = error.code
        } else {// 未知类型
            ctx.body = {
                msg: '未知型错误',
                error_code: 999,
                request: `${ctx.method} ${ctx.path}`
            }
            ctx.status = 500
        }
    }

}
module.exports = catchError

